import React, { Component, Fragment } from "react";
import { Chart, Tooltip, Geom, Coord, Legend, Guide } from "bizcharts";
import { DataView } from "@antv/data-set";
import numeral from "numeral";
import autoHeight from "../autoHeight";

const { Html } = Guide;

@autoHeight()
export default class Pie extends Component {
  state = {
    pieTotal: 0,
    legendData: []
  };

  componentDidMount() {
    this.getLegendData();
  }

  componentDidUpdate(prevProps) {
    const { data = [] } = this.props;
    if (
      prevProps.data &&
      prevProps.data.length !== data.length &&
      data.length
    ) {
      this.getLegendData();
    }
  }

  componentWillUnmount = () => {
    this.chart.clear();
    clearInterval(this.tm);
  };

  getActived = () => {
    const { data = [] } = this.props;
    let { legendData } = this.state;
    legendData = legendData.filter(k => k);
    let i = data.findIndex(k => k.x === legendData[0]);
    i = i === -1 ? 0 : i;
    if (i === -1 || !data.length || !this.chart) return;

    this.setState({
      pieTotal: data[i].y
    });
    this.tm = setTimeout(() => {
      const gemos = this.chart.getAllGeoms()[0];
      gemos.setShapeSelected(gemos.getShapes()[0], true);
    }, 500);
  };

  getLegendData = () => {
    const { data = [] } = this.props;
    const legendData = data.map(item => item.x);
    this.setState(
      {
        legendData
      },
      () => {
        this.getActived();
      }
    );
  };

  handleLegendClick = ({ item }) => {
    const { data } = this.props;
    const i = data.findIndex(k => k.x === item.value);
    if (i === -1) return;
    const { legendData } = this.state;
    legendData[i] = item.checked ? item.value : undefined;
    if (this.chart) {
      this.chart.filter("x", val => legendData.indexOf(val) > -1);
    }
    this.setState(
      {
        legendData
      },
      () => {
        this.getActived();
      }
    );
  };

  render() {
    if (this.chart) {
      this.chart.forceFit();
    }
    const {
      title,
      total = false,
      hasLegend = false,
      forceFit = true,
      style,
      height,
      percent,
      color,
      inner = 0.75,
      animate = false,
      colors,
      lineWidth = 1
    } = this.props;
    let { data = [], selected = true, tooltip = true } = this.props;
    let formatColor;
    const scale = {
      x: {
        type: "cat",
        range: [0, 1]
      },
      y: {
        min: 0
      }
    };
    let padding = [12, 200, 12, 12];

    const dv = new DataView();
    if (percent) {
      // padding = [12, 0, 12, 0];
      padding = 0;
      selected = false;
      tooltip = false;
      formatColor = value => {
        if (value === "占比") {
          return color || "rgba(24, 144, 255, 0.85)";
        }
        return "#F0F2F5";
      };
      data = [
        {
          x: "占比",
          y: percent
        }
      ];

      data = percent < 100 ? [...data, { x: "反比", y: 100 - percent }] : data;
    }
    const tooltipFormat = [
      "x*percent",
      (x, p) => ({
        name: `${x}：`,
        value: p ? `${Math.round(p * 100)}%` : "0%"
      })
    ];

    dv.source(data).transform({
      type: "percent",
      field: "y",
      dimension: "x",
      as: "percent"
    });
    const onPlotClick = ({ data: { _origin = {} } = {} } = {}) => {
      let { legendData } = this.state;
      legendData = legendData.filter(k => k);
      const current = legendData.findIndex(k => k === _origin.x);
      if (current > -1) {
        this.setState(
          {
            pieTotal: _origin.y
          },
          () => {
            const gemos = this.chart.getAllGeoms()[0];
            gemos.setShapeSelected(gemos.getShapes()[current], true);
          }
        );
      }
    };
    return (
      <Fragment>
        {title && (
          <h4>
            <strong>
              {title} {dv.state.num}
            </strong>
          </h4>
        )}
        <Chart
          scale={scale}
          forceFit={forceFit}
          data={dv}
          padding={padding}
          animate={animate}
          style={{ ...style }}
          height={height}
          onGetG2Instance={chart => {
            this.chart = chart;
          }}
          onPlotClick={onPlotClick}
        >
          {!!tooltip && (
            <Tooltip
              showTitle={false}
              g2-tooltip={{
                backgroundColor: "rgba(0,0,0,.75)",
                color: "#fff",
                boxShadow: "0px 2px 8px 0px rgba(0,0,0,0.15)"
              }}
              g2-tooltip-value={{
                float: "none",
                marginLeft: "0px"
              }}
            />
          )}
          <Coord type="theta" innerRadius={inner} />
          <Geom
            style={{ lineWidth, stroke: "#fff" }}
            tooltip={tooltip && tooltipFormat}
            type="intervalStack"
            position="percent"
            color={["x", percent ? formatColor : colors]}
            select={selected}
          />
          {hasLegend && (
            <Legend
              onClick={this.handleLegendClick}
              marker="circle"
              position="right-center"
              useHtml={true}
              itemTpl={(value, color2, checked, index) => {
                const obj = dv.rows[index] || {};
                const isChecked = checked ? "checked" : "unChecked";
                return `<li class="g2-legend-list-item item-${index} ${isChecked}" data-color="${color2}" data-value="${value}" style="cursor: pointer;font-size: 14px; "><i  class="g2-legend-marker" style="background-color: ${color2};"></i><span class="g2-legend-text" style="color:rgba(0,0,0,.45); 
                width:6em;max-width: 40%;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;   display: inline-block;" title=${value}>${value}</span><i style="display: inline-block;
                  margin: -3px 8px;
                  width: 1px;
                  height: 16px; background:rgba(0,0,0,.1)"></i>
                  <span className={styles.percent}>
                    ${
                      Number.isNaN(obj.percent)
                        ? 0
                        : Math.round(obj.percent * 100)
                    }%
                  </span> </li>`;
              }}
              g2-legend-marker={{
                width: "8px",
                height: "8px",
                marginRight: "8px",
                verticalAlign: "none"
              }}
              g2-legend-list-item={{
                marginRight: 0,
                marginBottom: "16px",
                marginLeft: "16px",
                whiteSpace: "nowrap",
                display: "flex",
                alignItems: "center"
              }}
            />
          )}
          {total && (
            <Guide>
              <Html
                position={["50%", "50%"]}
                html={`<p style="font-size: 14px;
                color: rgba(0, 0, 0, 0.45);
                display: flex;
                flex-direction: column;
                justify-content: center;
                margin: 0;
                text-align: center;" >
                <span>反馈数量</span>
                <span style="font-size: 30px;
                color: rgba(0, 0, 0, 0.85);
                white-space: nowrap;">
                  ${numeral(this.state.pieTotal).format("0,0")}
                </span>
              </p>`}
                alignX="middle"
                alignY="middle"
              />
            </Guide>
          )}
        </Chart>
      </Fragment>
    );
  }
}
